<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <!-- Bootstrap 布局依赖（解决 d-flex 等样式） -->
    <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
    >
    <!-- Font Awesome 图标依赖（解决 fas 图标） -->
    <link
            rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"
    >
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>气象小时数据管理</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <style type="text/tailwindcss">
        .card-shadow { box-shadow: 0 4px 20px rgba(30, 64, 175, 0.08); }
        .input-focus { @apply focus:border-blue-600 focus:ring-2 focus:ring-blue-200 transition-all; }
        .btn-primary { @apply bg-blue-700 hover:bg-blue-800 text-white px-4 py-2 rounded-lg transition-all; }
        .btn-secondary { @apply bg-gray-100 hover:bg-gray-200 text-gray-700 px-4 py-2 rounded-lg transition-all; }
        .pagination-btn:disabled { @apply opacity-50 cursor-not-allowed; }
        /* 顶部导航栏 */


        .top-nav {
            background: linear-gradient(90deg, var(--dark-bg) 0%, var(--primary-blue) 100%);
            color: white;
            padding: 0.8rem 0;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .nav-brand {
            font-size: 1.5rem;
            font-weight: 600;
            display: flex;
            align-items: center;
        }
    </style>


</head>
<body class="bg-gray-50 min-h-screen">
<div class="container mx-auto px-4 py-8">
    <!-- 顶部操作栏 -->
  <!--  &lt;!&ndash; 顶部导航栏 &ndash;&gt;
    <div class="top-nav">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center">
                <div class="nav-brand">

                    <span>气象数据增改模块</span>
                </div>
                <div class="text-end">
                    <span class="me-3"><span id="lastUpdateTime">&#45;&#45;</span></span>
                </div>
            </div>
        </div>
    </div>-->
    <div class="bg-white rounded-xl p-6 card-shadow mb-6">
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
                <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">气象小时数据管理</h1>
                <p class="text-gray-500 mt-1">支持新增、编辑小时级气象与土壤数据</p>
            </div>
            <div class="flex flex-wrap gap-3">
                <!-- 时间筛选 -->
                <div class="flex items-center gap-2 bg-gray-50 p-2 rounded-lg">
                    <label for="startDate" class="text-gray-600">开始日期：</label>
                    <input type="date" id="startDate" class="border border-gray-300 rounded-md px-3 py-1.5 input-focus">
                </div>
                <div class="flex items-center gap-2 bg-gray-50 p-2 rounded-lg">
                    <label for="endDate" class="text-gray-600">结束日期：</label>
                    <input type="date" id="endDate" class="border border-gray-300 rounded-md px-3 py-1.5 input-focus">
                </div>
                <!-- 刷新按钮（加ID） -->
                <button id="refreshBtn" class="btn-secondary flex items-center gap-1">
                    <i class="fa fa-refresh"></i> 刷新
                </button>
                <!-- 新增按钮 -->
                <button id="addBtn" class="btn-primary flex items-center gap-1">
                    <i class="fa fa-plus"></i> 新增数据
                </button>
            </div>
        </div>
    </div>

    <!-- 数据列表区 -->
    <div class="bg-white rounded-xl card-shadow overflow-hidden">
        <div class="p-4 border-b border-gray-100 flex items-center justify-between">
            <h2 class="font-semibold text-gray-700">气象数据列表</h2>
            <!-- 总记录数（加ID） -->
            <p class="text-sm text-gray-500" id="totalRecords">共 0 条记录</p>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                <tr class="bg-gray-50 text-left">
                    <th class="px-6 py-3 text-sm font-medium text-gray-600">观测时间</th>
                    <th class="px-6 py-3 text-sm font-medium text-gray-600">气温(°C)</th>
                    <th class="px-6 py-3 text-sm font-medium text-gray-600">相对湿度(%)</th>
                    <th class="px-6 py-3 text-sm font-medium text-gray-600">降水量(mm)</th>
                    <th class="px-6 py-3 text-sm font-medium text-gray-600">土壤湿度(m³/m³)</th>
                    <th class="px-6 py-3 text-sm font-medium text-gray-600">操作</th>
                </tr>
                </thead>
                <!-- 动态表格体（清空静态行） -->
                <tbody class="divide-y divide-gray-100" id="tableBody"></tbody>
            </table>
        </div>
        <!-- 分页容器（清空静态按钮，加class） -->
        <div class="p-4 border-t border-gray-100 flex justify-between items-center">
            <div class="text-sm text-gray-500" id="pageInfo">显示 0-0 条</div>
            <div class="flex gap-2 pagination" id="pagination"></div>
        </div>
    </div>
</div>

<!-- 表单弹窗 -->
<div id="formModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
    <div class="bg-white rounded-xl w-full max-w-4xl max-h-[90vh] overflow-auto">
        <div class="p-6 border-b border-gray-100 flex justify-between items-center sticky top-0 bg-white z-10">
            <h2 id="formTitle" class="text-xl font-bold text-gray-800">新增气象小时数据</h2>
            <button id="closeModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                <i class="fa fa-times text-xl"></i>
            </button>
        </div>
        <form id="dataForm" class="p-6">
            <!-- 编辑ID隐藏域 -->
            <input type="hidden" id="recordId" />
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- 基础气象数据 -->
                <div class="bg-blue-50 rounded-lg p-5 card-shadow">
                    <h3 class="font-semibold text-blue-800 mb-4 flex items-center gap-2">
                        <i class="fa fa-cloud"></i> 基础气象数据
                    </h3>
                    <div class="space-y-4">
                        <div>
                            <label for="time" class="block text-sm font-medium text-gray-700 mb-1">观测时间 <span class="text-red-500">*</span></label>
                            <input type="datetime-local" id="time" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus" required>
                        </div>
                        <div>
                            <label for="temperature2m" class="block text-sm font-medium text-gray-700 mb-1">2米气温(°C)</label>
                            <input type="number" id="temperature2m" step="0.1" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                        </div>
                        <div>
                            <label for="relativehumidity2m" class="block text-sm font-medium text-gray-700 mb-1">2米相对湿度(%)</label>
                            <input type="number" id="relativehumidity2m" min="0" max="100" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                        </div>
                        <div>
                            <label for="dewpoint2m" class="block text-sm font-medium text-gray-700 mb-1">2米露点温度(°C)</label>
                            <input type="number" id="dewpoint2m" step="0.1" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                        </div>
                        <div>
                            <label for="windspeed10m" class="block text-sm font-medium text-gray-700 mb-1">10米风速(m/s)</label>
                            <input type="number" id="windspeed10m" step="0.1" min="0" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                        </div>
                        <div>
                            <label for="winddirection100m" class="block text-sm font-medium text-gray-700 mb-1">100米风向(°)</label>
                            <input type="number" id="winddirection100m" min="0" max="360" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                        </div>
                    </div>
                </div>

                <!-- 气压与降水数据 -->
                <div class="bg-indigo-50 rounded-lg p-5 card-shadow">
                    <h3 class="font-semibold text-indigo-800 mb-4 flex items-center gap-2">
                        <i class="fa fa-tint"></i> 气压与降水数据
                    </h3>
                    <div class="space-y-4">
                        <div>
                            <label for="weathercode" class="block text-sm font-medium text-gray-700 mb-1">天气代码</label>
                            <input type="number" id="weathercode" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                        </div>
                        <div>
                            <label for="pressureMsl" class="block text-sm font-medium text-gray-700 mb-1">海平面气压(hPa)</label>
                            <input type="number" id="pressureMsl" step="0.1" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                        </div>
                        <div>
                            <label for="surfacePressure" class="block text-sm font-medium text-gray-700 mb-1">地面气压(hPa)</label>
                            <input type="number" id="surfacePressure" step="0.1" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                        </div>
                        <div>
                            <label for="precipitation" class="block text-sm font-medium text-gray-700 mb-1">降水量(mm)</label>
                            <input type="number" id="precipitation" step="0.1" min="0" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                        </div>
                        <div>
                            <label for="et0FaoEvapotranspiration" class="block text-sm font-medium text-gray-700 mb-1">FAO参考蒸散量(mm)</label>
                            <input type="number" id="et0FaoEvapotranspiration" step="0.1" min="0" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                        </div>
                    </div>
                </div>

                <!-- 土壤数据 -->
                <div class="bg-green-50 rounded-lg p-5 card-shadow md:col-span-2">
                    <h3 class="font-semibold text-green-800 mb-4 flex items-center gap-2">
                        <i class="fa fa-leaf"></i> 土壤温湿度数据
                    </h3>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                        <div class="space-y-4">
                            <div>
                                <label for="soilTemperature0To7cm" class="block text-sm font-medium text-gray-700 mb-1">0-7cm土壤温度(°C)</label>
                                <input type="number" id="soilTemperature0To7cm" step="0.1" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                            </div>
                            <div>
                                <label for="soilMoisture0To7cm" class="block text-sm font-medium text-gray-700 mb-1">0-7cm土壤湿度(m³/m³)</label>
                                <input type="number" id="soilMoisture0To7cm" step="0.01" min="0" max="1" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                            </div>
                        </div>
                        <div class="space-y-4">
                            <div>
                                <label for="soilTemperature7To28cm" class="block text-sm font-medium text-gray-700 mb-1">7-28cm土壤温度(°C)</label>
                                <input type="number" id="soilTemperature7To28cm" step="0.1" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                            </div>
                            <div>
                                <label for="soilMoisture7To28cm" class="block text-sm font-medium text-gray-700 mb-1">7-28cm土壤湿度(m³/m³)</label>
                                <input type="number" id="soilMoisture7To28cm" step="0.01" min="0" max="1" class="w-full border border-gray-300 rounded-md px-3 py-2 input-focus">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 提交按钮区 -->
            <div class="mt-8 flex justify-end gap-3">
                <button type="button" id="cancelBtn" class="btn-secondary">取消</button>
                <button type="button" id="submitBtn" class="btn-primary">提交数据</button>
            </div>
        </form>
    </div>
</div>

<!-- 核心交互脚本 -->
<script>

    document.addEventListener('DOMContentLoaded', () => {
        // ========== 1. 全局变量与元素绑定 ==========
        let currentPage = 1;        // 当前页码
        const pageSize = 10;        // 每页条数
        // 元素绑定（与HTML ID严格对应）
        const $startDate = document.getElementById('startDate');
        const $endDate = document.getElementById('endDate');
        const $refreshBtn = document.getElementById('refreshBtn');
        const $tableBody = document.getElementById('tableBody');
        const $pagination = document.getElementById('pagination');
        const $totalRecords = document.getElementById('totalRecords');
        const $pageInfo = document.getElementById('pageInfo');
        const $formModal = document.getElementById('formModal');
        const $recordId = document.getElementById('recordId');
        const $submitBtn = document.getElementById('submitBtn');
        const $addBtn = document.getElementById('addBtn');
        const $closeModal = document.getElementById('closeModal');
        const $cancelBtn = document.getElementById('cancelBtn');

        // ========== 2. 初始化：绑定事件 ==========
        $refreshBtn.addEventListener('click', handleRefresh);
        $addBtn.addEventListener('click', handleAdd);
        $tableBody.addEventListener('click', handleTableClick);
        $closeModal.addEventListener('click', () => $formModal.classList.add('hidden'));
        $cancelBtn.addEventListener('click', () => $formModal.classList.add('hidden'));
        $submitBtn.addEventListener('click', handleSubmit);

        // 首次加载数据
        loadData();

        // ========== 3. 核心函数：加载数据（分页+时间筛选） ==========
        async function loadData() {
            try {
                $tableBody.innerHTML = '<tr><td colspan="6" class="text-center py-4">加载中...</td></tr>';

                const res = await axios.get('/api/weather-hourly/page', {
                    params: {
                        pageNum: currentPage,
                        pageSize: pageSize,
                        startDate: $startDate.value,
                        endDate: $endDate.value
                    }
                });

                // 后端返回的 IPage 结构：
                // { records: [...], total: 1512, pages: 152, current: 1, size: 10 }
                const { records, total, pages } = res.data.data;
                renderTable(records);
                renderPagination(pages, total); // 传递总页数和总记录数
            } catch (error) {
                $tableBody.innerHTML = `<tr><td colspan="6" class="text-center py-4 text-red-500">加载失败：${error.message}</td></tr>`;
            }
        }

        // ========== 4. 渲染表格（动态数据） ==========
        function renderTable(records) {
            if (records.length === 0) {
                $tableBody.innerHTML = '<tr><td colspan="6" class="text-center py-4">暂无数据</td></tr>';
                return;
            }

            let html = '';
            records.forEach(item => {
                html += `
                    <tr class="card-hover">
                        <td class="px-6 py-4 text-sm text-gray-800">${item.time.replace('T', ' ')}</td>
                        <td class="px-6 py-4 text-sm text-gray-700">${item.temperature2m || '-'}</td>
                        <td class="px-6 py-4 text-sm text-gray-700">${item.relativehumidity2m || '-'}</td>
                        <td class="px-6 py-4 text-sm text-gray-700">${item.precipitation || '-'}</td>
                        <td class="px-6 py-4 text-sm text-gray-700">${item.soilMoisture0To7cm || '-'}</td>
                        <td class="px-6 py-4 text-sm">
                            <button class="edit-btn text-blue-600 hover:text-blue-800 transition-colors" data-id="${item.id}">
                                <i class="fa fa-pencil mr-1"></i>编辑
                            </button>
                        </td>
                    </tr>`;
            });
            $tableBody.innerHTML = html;
        }

        // ========== 5. 渲染分页（动态按钮） ==========
        function renderPagination(totalPages, total) {
            if (totalPages === 0) {
                $pagination.innerHTML = '';
                $totalRecords.textContent = `共 0 条记录`;
                $pageInfo.textContent = `显示 0-0 条`;
                return;
            }
            // 存储总页数到dataset，供changePage使用
            $pagination.dataset.totalPages = totalPages;
            let html = '';
            // 上一页
            html += `
    <button class="btn-secondary text-sm px-3 py-1 pagination-btn"
            onclick="changePage(${currentPage - 1})"
            ${currentPage === 1 ? 'disabled' : ''}>
        上一页
    </button>`;

            // 页码：最多显示5个（当前页±2）
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, startPage + 4);
            for (let i = startPage; i <= endPage; i++) {
                html += `
        <button class="btn-secondary text-sm px-3 py-1 pagination-btn ${i === currentPage ? 'bg-blue-700 text-white' : ''}"
                onclick="changePage(${i})">
            ${i}
        </button>`;
            }

            // 下一页
            html += `
    <button class="btn-secondary text-sm px-3 py-1 pagination-btn"
            onclick="changePage(${currentPage + 1})"
            ${currentPage === totalPages ? 'disabled' : ''}>
        下一页
    </button>`;

            $pagination.innerHTML = html;
            $totalRecords.textContent = `共 ${total} 条记录`;
            $pageInfo.textContent = `显示 ${(currentPage - 1) * pageSize + 1}-${Math.min(currentPage * pageSize, total)} 条`;
        }

        // ========== 6. 切换页码（全局函数） ==========
        window.changePage = function(page) {
            const totalPages = +$pagination.dataset.totalPages; // 从dataset取总页数（转数字）
            if (page < 1 || page > totalPages) return; // 严格校验
            currentPage = page;
            loadData(); // 重载当前页
        };

        // ========== 7. 事件委托：编辑按钮 ==========
        function handleTableClick(e) {
            if (e.target.classList.contains('edit-btn')) {
                const id = e.target.dataset.id;
                if (!id) return alert('数据ID异常！');
                $recordId.value = id;
                $formModal.querySelector('h2').textContent = '编辑气象小时数据';
                // 调用后端接口，填充表单（需补充：axios.get(`/api/weather-hourly/${id}`) 后赋值）
                // 示例：假设后端返回数据结构与实体类一致
                axios.get(`/api/weather-hourly/${id}`).then(res => {
                    const data = res.data.data;
                    document.getElementById('time').value = data.time;
                    document.getElementById('temperature2m').value = data.temperature2m;
                    document.getElementById('relativehumidity2m').value = data.relativehumidity2m;
                    document.getElementById('dewpoint2m').value = data.dewpoint2m;
                    document.getElementById('windspeed10m').value = data.windspeed10m;
                    document.getElementById('winddirection100m').value = data.winddirection100m;
                    document.getElementById('weathercode').value = data.weathercode;
                    document.getElementById('pressureMsl').value = data.pressureMsl;
                    document.getElementById('surfacePressure').value = data.surfacePressure;
                    document.getElementById('precipitation').value = data.precipitation;
                    document.getElementById('et0FaoEvapotranspiration').value = data.et0FaoEvapotranspiration;
                    document.getElementById('soilTemperature0To7cm').value = data.soilTemperature0To7cm;
                    document.getElementById('soilMoisture0To7cm').value = data.soilMoisture0To7cm;
                    document.getElementById('soilTemperature7To28cm').value = data.soilTemperature7To28cm;
                    document.getElementById('soilMoisture7To28cm').value = data.soilMoisture7To28cm;
                }).catch(err => {
                    alert(`数据加载失败：${err.message}`);
                });
                $formModal.classList.remove('hidden');
            }
        }

        // ========== 8. 新增按钮逻辑 ==========
        function handleAdd() {
            $formModal.querySelector('h2').textContent = '新增气象小时数据';
            document.getElementById('dataForm').reset();
            $recordId.value = '';
            $formModal.classList.remove('hidden');
        }

        // ========== 9. 表单提交逻辑（新增/编辑） ==========
        async function handleSubmit() {
            // 收集表单数据
            const formData = {
                time: document.getElementById('time').value,
                temperature2m: document.getElementById('temperature2m').value ? parseFloat(document.getElementById('temperature2m').value) : null,
                relativehumidity2m: document.getElementById('relativehumidity2m').value ? parseInt(document.getElementById('relativehumidity2m').value) : null,
                dewpoint2m: document.getElementById('dewpoint2m').value ? parseFloat(document.getElementById('dewpoint2m').value) : null,
                windspeed10m: document.getElementById('windspeed10m').value ? parseFloat(document.getElementById('windspeed10m').value) : null,
                winddirection100m: document.getElementById('winddirection100m').value ? parseInt(document.getElementById('winddirection100m').value) : null,
                weathercode: document.getElementById('weathercode').value ? parseInt(document.getElementById('weathercode').value) : null,
                pressureMsl: document.getElementById('pressureMsl').value ? parseFloat(document.getElementById('pressureMsl').value) : null,
                surfacePressure: document.getElementById('surfacePressure').value ? parseFloat(document.getElementById('surfacePressure').value) : null,
                precipitation: document.getElementById('precipitation').value ? parseFloat(document.getElementById('precipitation').value) : null,
                et0FaoEvapotranspiration: document.getElementById('et0FaoEvapotranspiration').value ? parseFloat(document.getElementById('et0FaoEvapotranspiration').value) : null,
                soilTemperature0To7cm: document.getElementById('soilTemperature0To7cm').value ? parseFloat(document.getElementById('soilTemperature0To7cm').value) : null,
                soilMoisture0To7cm: document.getElementById('soilMoisture0To7cm').value ? parseFloat(document.getElementById('soilMoisture0To7cm').value) : null,
                soilTemperature7To28cm: document.getElementById('soilTemperature7To28cm').value ? parseFloat(document.getElementById('soilTemperature7To28cm').value) : null,
                soilMoisture7To28cm: document.getElementById('soilMoisture7To28cm').value ? parseFloat(document.getElementById('soilMoisture7To28cm').value) : null,
            };

            // 必填校验
            if (!formData.time) {
                return alert('观测时间为必填项！');
            }

            try {
                const isEdit = $formModal.querySelector('h2').textContent.includes('编辑');
                if (isEdit) {
                    await axios.put(`/api/weather-hourly/${$recordId.value}`, formData);
                } else {
                    await axios.post('/api/weather-hourly', formData);
                }
                $formModal.classList.add('hidden');
                await handleRefresh(); // 提交后刷新
                alert('操作成功！');
            } catch (error) {
                alert(`操作失败：${error.message}`);
            }
        }

        // ========== 10. 刷新逻辑（重置页码+重新加载） ==========
        function handleRefresh() {
            currentPage = 1;
            loadData();
        }
    });
</script>
</body>
</html>
